package top.fullj.ctx;

import com.google.common.base.MoreObjects;
import top.fullj.bean.ToString;

import javax.annotation.Nonnull;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author bruce.wu
 * @since 2021/12/8 11:29
 */
public class ContextBase implements Context {

    private final Map<Object, Object> items;

    public ContextBase() {
        this(false);
    }

    public ContextBase(boolean threadsafe) {
        this.items = threadsafe ? new ConcurrentHashMap<>() : new HashMap<>();
    }

    @Override
    public boolean hasAttr(@Nonnull Object key) {
        return items.containsKey(key);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T getAttr(@Nonnull Object key) {
        return (T) items.get(key);
    }

    @Override
    public ContextBase setAttr(@Nonnull Object key, @Nonnull Object value) {
        items.put(key, value);
        return this;
    }

    @Override
    public void remove(@Nonnull Object key) {
        items.remove(key);
    }

    @Override
    @Nonnull
    public Map<Object, ?> toMap() {
        return Collections.unmodifiableMap(items);
    }

    @Override
    public String toString() {
        MoreObjects.ToStringHelper helper = ToString.toStringHelper(this);
        for (Map.Entry<Object, Object> entry : items.entrySet()) {
            helper.add(String.valueOf(entry.getKey()), entry.getValue());
        }
        return helper.toString();
    }

}
